package pubsub

import (
	"errors"
	"gitee.com/liukexing/mqbroker/core/driver/logger"
	"gitee.com/liukexing/mqbroker/core/typedef"
	"time"
)

type MessageReplyHandle struct {
	Method map[string]func(interface{}) (interface{}, error)
}

func (m *MessageReplyHandle) Praise(v interface{}) (interface{}, bool) {
	data := typedef.ReplyMsgData{}
	if logger.CheckErr(typedef.ErrInfo{
		Err: typedef.Decode(v, &data),
	}) {
		return nil, true
	}
	return data, false
}
func (m *MessageReplyHandle) Process(data interface{}) (interface{}, error) {
	req := data.(typedef.ReplyMsgData)
	if v, ok := m.Method[req.Method]; ok {
		return v(req.Data)
	}
	return nil, errors.New("Method Not Found")
}

func MessageReplyServer(info typedef.ModuleInfo, method map[string]func(interface{}) (interface{}, error)) bool {
	return Server.AddReply(info.ID, &MessageReplyHandle{
		Method: method,
	})
}

func MessageReplyClient(name, method string, data interface{}, delay time.Duration) typedef.ResponseData {
	return Server.Request(name, &typedef.ReplyMsgData{
		Method: method,
		Data:   data,
	}, delay*time.Second)
}
